<template>
    <div>
        <Form :label-width="80" ref="formInline" :model="formInline">
            <Row :gutter="16" class="query-form2">
                <i-col span="8">
                    <FormItem label="标题：">
                        <Input v-model="formInline.title" placeholder="请填写观察人员"/>
                    </FormItem>
                </i-col>
                <i-col span="16">
                    <div style="float: right;">
                        <Button class="ivu-btn-query"  icon="md-search"  @click="query">查询</Button>
                        <Button class="ivu-btn-reset" style="margin-left: 10px" @click="cancel">重置</Button>
                    </div>
                </i-col>
            </Row>
        </Form>
        <Row type="flex" justify="start" class="query-form">
            <i-col>
                <Button icon="md-add" class="ivu-btn-add" @click="addInfo">新增</Button>
            </i-col>
        </Row>
        <Table ref='table' style="margin-top: 10px" :loading="loading" border :columns="columns" no-data-text="没有查询到相关数据！"
               :data="infos" width="100%" :height="tableHeight" highlight-row stripe size="small"></Table>
        <Row type="flex" justify="end" >
            <i-col>
                <Page :total="pagedata.total" :current="pagedata.currentPage" :page-size="pagedata.pageSize"
                      @on-page-size-change="pageSizeChange" @on-change="pageChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
            </i-col>
        </Row>

        <Modal :title="modalTitle" :transfer=false v-model="modal1" :width=1200>
            <div :style="{height: divHeight, overflowY: 'auto', overflowX: 'hidden'}">
                <Form :model="formData" ref="infoCustom"  label-position="top" :rules="ruleCustom">
                    <Row type="flex" justify="space-around" class="code-row-bg" :gutter="16">
                        <i-col span="12">
                            <FormItem label="所属公司：" prop="orgId">
                                <orgDom ref="orgDom" @setOrgInfo="setOrgName" :orgInfo="{name: formData.orgName}"></orgDom>
                            </FormItem>
                        </i-col>
                        <i-col span="12">
                            <FormItem label="标题：" prop="title">
                                <Input v-model="formData.title" maxlength="255"  show-word-limit />
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row type="flex" justify="space-around" class="code-row-bg" :gutter="16">
                        <i-col span="12">
                            <FormItem label="环保画像标准：" prop="standardId">
                                <Select v-model="formData.standardId" filterable @on-change="standardChange">
                                    <Option v-for="item in standardList" :value="item.standardId">{{item.title}}</Option>
                                </Select>
                            </FormItem>
                        </i-col>
                        <i-col span="12">
                        </i-col>
                    </Row>
                    <Table ref='table2' :loading="loading2" border :columns="standardColumns" no-data-text="请选择环保画像标准！" :span-method="handleSpan"
                           :data="standardInfos" width="100%" height="500" highlight-row stripe size="small"></Table>
                </Form>
            </div>
            <div slot="footer">
                <Button type="primary" class='ivu-btn-save' :loading="buttonLoading" @click="saveInfo()" v-if="isButton">确定</Button>
                <Button type="primary" class='ivu-btn-cancel' @click="modal1=false" style="margin-left: 2px">取消</Button>
            </div>
        </Modal>
        <Modal :title="modalTitle" :transfer=false v-model="modal2" :width=800>
            <Table ref='table3' :loading="loading2" border :columns="recordColumns" no-data-text="请选择环保画像标准！" :span-method="handleSpan"
                   :data="recordInfos" width="100%" height="400" highlight-row stripe size="small"></Table>
            <div slot="footer">
                <Button type="primary" class='ivu-btn-cancel' @click="modal2=false" style="margin-left: 2px">取消</Button>
            </div>
        </Modal>
    </div>
</template>

<script>

    import {sessionStorage} from '@/common/cacheUtils.js';
    import orgDom from "@/components/input-org.vue";
    import {Api} from '../../../api/index.js'

    export default {
        name: "tailoring",
        components:{
            orgDom,
        },
        data(){
            return {
                isButton: false,
                modalTitle: '',
                buttonLoading: false,
                modal1: false,
                modal2: false,
                formData: {},
                formInline: {},
                loading: false,
                loading2: false,
                columns: [
                    {
                        title: '序号',
                        width: 80,
                        align: 'center',
                        fixed: 'left',
                        render: this.indexColumnsRender
                    },
                    {
                        title: '所属机构',
                        align: 'center',
                        key: 'orgName',
                        minWidth: 120,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.orgName || '--')
                            ]);
                        }
                    },
                    {
                        title: '标题',
                        align: 'center',
                        key: 'title',
                        minWidth: 120,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.title || '--')
                            ]);
                        }
                    },
                    {
                        title: '创建人',
                        align: 'center',
                        key: 'userName',
                        minWidth: 120,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.userName || '--')
                            ]);
                        }
                    },
                    {
                        title: '创建时间',
                        align: 'center',
                        key: 'createDate',
                        minWidth: 120,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',this.formatDate(new Date(params.row.createDate), 'yyyy-MM-dd hh:mm:ss'))
                            ]);
                        }
                    },
                    {
                        title: '最近更新时间',
                        align: 'center',
                        key: 'createDate',
                        minWidth: 120,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',this.formatDate(new Date(params.row.updateDate), 'yyyy-MM-dd hh:mm:ss'))
                            ]);
                        }
                    },
                    {
                        title: '操作',
                        align: 'center',
                        key: 'view',
                        fixed: 'right',
                        minWidth: 200,
                        render: (h, params) => {
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px'
                                    },
                                    on: {
                                        click: () => {

                                            this.updateRow(params.row);
                                            this.modal2 = true;
                                        }
                                    }
                                }, '详情'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                    },
                                    on: {
                                        click: () => {
                                            this.isButton = true;
                                            this.modalTitle = "修改";
                                            this.isUpdate = true;
                                            this.formData = params.row;
                                            setTimeout(() => {
                                                this.$refs.orgDom.setCurrentOrg();
                                            }, 300);
                                            this.updateRow(params.row);
                                            this.modal1 = true;
                                        }
                                    }
                                }, '修改'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: 'red',
                                    },
                                    on: {
                                        click: () => {
                                            this.deleteRow(params.row);
                                        }
                                    }
                                }, '删除'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                    },
                                    on: {
                                        click: () => {
                                            this.modalTitle = "修改记录";
                                            this.selectRow = params.row;
                                            this.recordRow(params.row);
                                            this.modal2 = true;
                                            this.isButton = false;
                                        }
                                    }
                                }, '修改记录'),

                            ]);
                        }
                    }
                ],
                infos: [],
                tableHeight: '',
                divHeight: '',
                pagedata: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1,
                },
                pageSizeArray: [10, 20, 50],
                ruleCustom: {
                    orgId: [{
                        required: true,
                        message: '  ',
                        trigger: 'blur, change'
                    }],
                    title: [{
                        required: true,
                        message: '  ',
                        trigger: 'blur, change'
                    }],
                    standardId: [{
                        required: true,
                        message: '  ',
                        trigger: 'blur, change'
                    }]
                },
                userInfo: sessionStorage('userId').getObject('userId'),
                standardList: [],
                codingList1: [],
                codingList2: [],
                codingList3: [],
                orgName: '',
                classification: '',
                isUpdate: false,
                standardColumns: [
                    {
                        width: 80,
                        type: 'selection',
                        align: 'center',
                        fixed: 'left',
                    },
                    {
                        title: '画像标准',
                        align: 'center',
                        key: 'standardName',
                        minWidth: 120,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.standardName || '--')
                            ]);
                        }
                    },
                    {
                        title: '标准子项',
                        align: 'center',
                        key: 'subitemName',
                        minWidth: 120,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.subitemName || '--')
                            ]);
                        }
                    },
                    {
                        title: '管理要素',
                        align: 'center',
                        key: 'managementElements',
                        minWidth: 100,
                        render:(h,params)=>{
                            let value = '';
                            this.codingList1.forEach(i =>{
                                if(i.codingCodeId == params.row.managementElements) value = i.codingName;
                            })
                            return h('div',[
                                h('span',value || '--')
                            ]);
                        }
                    },
                    {
                        title: '污染因子',
                        align: 'center',
                        key: 'pollutionFactor',
                        minWidth: 100,
                        render:(h,params)=>{
                            let value = '';
                            this.codingList2.forEach(i =>{
                                if(i.codingCodeId == params.row.pollutionFactor) value = i.codingName;
                            })
                            return h('div',[
                                h('span',value || '--')
                            ]);
                        }
                    },
                    {
                        title: '法律责任',
                        align: 'center',
                        key: 'legalResponsibility',
                        tooltip: true,
                        minWidth: 100,
                    },
                    {
                        title: '法律法规依据',
                        align: 'center',
                        key: 'lawsRegulations',
                        tooltip: true,
                        minWidth: 100
                    },
                    {
                        title: '风险等级',
                        align: 'center',
                        key: 'riskLevel',
                        minWidth: 100,
                        render:(h,params)=>{
                            let value = '';
                            this.codingList3.forEach(i =>{
                                if(i.codingCodeId == params.row.riskLevel) value = i.codingName;
                            })
                            return h('div',[
                                h('span',value || '--')
                            ]);
                        }
                    },
                ],
                standardInfos: [],
                recordColumns: [
                    {
                        title: '序号',
                        width: 80,
                        align: 'center',
                        render: this.indexColumnsRender
                    },
                    {
                        title: '修改时间',
                        align: 'center',
                        key: 'orgName',
                        minWidth: 120,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',this.formatDate(new Date(params.row.createDate), 'yyyy-MM-dd hh:mm:ss'))
                            ]);
                        }
                    },
                    {
                        title: '修改人',
                        align: 'center',
                        key: 'userName',
                        minWidth: 120,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.userName || '--')
                            ]);
                        }
                    },
                    {
                        title: '操作',
                        align: 'center',
                        key: 'view',
                        minWidth: 80,
                        render: (h, params) => {
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px'
                                    },
                                    on: {
                                        click: () => {
                                            this.modal1 = true;
                                            this.formData = this.selectRow;
                                            this.recordDetailRow(params.row);
                                        }
                                    }
                                }, '修改明细'),
                            ]);
                        }
                    }
                ],
                recordInfos: [],
                selectRow: {}
            }
        },
        watch: {
            "modal1": function (qw,er) {
                if(!qw){
                    this.formData = {};
                    this.standardInfos = [];
                    this.$refs.orgDom.resetCurrentOrg();

                }
            },
        },
        mounted(){
            this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
            this.divHeight = window.innerHeight - 150 +'px';
            this.query();
            this.queryStandard();
        },
        methods: {
            query(){
                this.loading = true;
                let data = {
                    startPage: this.pagedata.currentPage,
                    size: this.pagedata.pageSize,
                    conditions : this.formInline
                };
                this.$http.get(Api.queryEcoPortraitStandardTailoring, {
                    params: data
                }).then(function(res){
                    this.infos = res.data.data.data;
                    this.pagedata.total = res.data.data.totalSize;
                    this.loading = false;
                }, function(res){
                    this.$Message.error('请求失败');
                });
            },
            cancel(){
                this.formInline = {};
                this.query();
            },
            pageSizeChange(pageSize){
                this.pagedata.pageSize = pageSize;
                this.query();
            },
            pageChange(pageNum){
                this.pagedata.currentPage = pageNum;
                this.query();
            },
            addInfo(){
                this.modal1 = true;
                this.isUpdate = false;
                this.isButton = true;
                this.modalTitle = '新增'
            },
            updateRow(row){
                this.loading2 = true;
                this.$http.get(Api.queryEcoPortraitStandardTailoringDetail + '/all', {
                    params: {standardId: row.standardId, recordId: row.lastRecordId}
                }).then(function(res){
                    this.standardInfos = res.data.data;
                    this.integratedData(this.standardInfos);
                    this.standardInfos.forEach(i =>{
                        if(i.id != null) this.$set(i, '_checked', true);
                    })
                    this.loading2 = false;
                }, function(res){
                    this.$Message.error('请求失败');
                });
            },
            deleteRow(row){
                this.$Modal.confirm({
                    title: '数据删除',
                    content: '<p>确定删除该条信息</p>',
                    okText: '确认',
                    onOk: () => {
                        this.$http.delete(Api.deleteEcoPortraitStandardTailoring, {params:{
                                tailoringId: row.tailoringId,
                                updateUserId: this.userInfo.userId,
                            }}).then((res) => {
                            this.$Message.success({content:'删除成功',duration: 4});
                            this.query();
                        })
                    },
                    cancelText: '取消'
                });
            },
            recordRow(row){
                this.loading2 = true;
                this.$http.get(Api.queryEcoPortraitStandardTailoringRecord, {
                    params: {tailoringId: row.tailoringId}
                }).then(function(res){
                    this.recordInfos = res.data.data;
                    this.loading2 = false;
                }, function(res){
                    this.$Message.error('请求失败');
                });
            },
            recordDetailRow(row){
                this.loading2 = true;
                this.$http.get(Api.queryEcoPortraitStandardTailoringDetail, {
                    params: {recordId: row.recordId}
                }).then(function(res){
                    this.standardInfos = res.data.data;
                    this.integratedData(this.standardInfos);
                    this.standardInfos.forEach(i=>{ this.$set(i, '_checked', true); });
                    this.loading2 = false;
                }, function(res){
                    this.$Message.error('请求失败');
                });
            },
            indexColumnsRender(h, params){
                return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
            },
            queryStandard(){
                this.$http.get(Api.queryEcoPortraitStandard, {
                    params: { orgId: this.userInfo.twoLevelOrgId }
                }).then(function(res){
                    if(res.data.status == 200){
                        this.standardList = res.data.data;
                    }
                });
                this.$http.get(Api.queryCodeDetailBySortId + '/eco-00001', {params: {}}).then((res) => {
                    this.codingList1 = res.data.data;
                });
                this.$http.get(Api.queryCodeDetailBySortId + '/eco-00002', {params: {}}).then((res) => {
                    this.codingList2 = res.data.data;
                });
                this.$http.get(Api.queryCodeDetailBySortId + '/eco-00003', {params: {}}).then((res) => {
                    this.codingList3 = res.data.data;
                });
            },
            setOrgName(data){
                this.formData.orgId = data.orgId;
                this.orgName = data.orgName;
                this.$set(this.formData, 'title', data.orgName + "_" + this.classification);
            },
            saveInfo(){
                this.$refs['infoCustom'].validate((valid) => {
                    if(valid){
                        let arr = this.$refs.table2.getSelection();
                        if(arr.length == 0){
                            this.$Message.error({  content: '请选择环保画像标准！', duration: 4 });
                            return ;
                        }
                        this.formData.tailoringDetail = arr;
                        this.formData.createUserId = this.userInfo.userId;
                        this.formData.updateUserId = this.userInfo.userId;
                        if(this.isUpdate){
                            this.$http.put(Api.updateEcoPortraitStandardTailoring,this.formData).then(function(response){
                                this.buttonLoading = false;
                                this.modal1 = false;
                                this.query();
                                this.$Message.success({  content: '保存成功', duration: 4 });
                            });
                        }else{
                            this.$http.post(Api.saveEcoPortraitStandardTailoring, this.formData).then(function(response){
                                this.buttonLoading = false;
                                this.modal1 = false;
                                this.query();
                                this.$Message.success({  content: '保存成功', duration: 4 });
                            });
                        }
                    }
                });
            },
            standardChange(item){
                this.standardList.forEach(i=> {
                    if(i.standardId == item) this.classification = i.title;
                });
                this.$set(this.formData, 'title', this.orgName + "_" + this.classification);
                //加载环保画像标准明细
                this.loading2 = true;
                this.$http.get(Api.queryEcoPortraitStandardDetailStandard, {
                    params: {standardId:  item}
                }).then(function(res){
                    this.standardInfos =res.data.data;
                    this.integratedData(this.standardInfos);
                    this.loading2 = false;
                }, function(res){
                    this.$Message.error('请求失败');
                });
            },
            integratedData(data){
                let arrId = [];
                let arrId2 = [];
                data.forEach(i => {
                    !arrId.includes(i.standardId) ? arrId.push(i.standardId) : arrId;
                    !arrId2.includes(i.subitemId) ? arrId2.push(i.subitemId) : arrId2;
                });
                let arrObj = [];
                let arrObj2 = [];
                arrId.forEach(j => {
                    arrObj.push({
                        id: j,
                        num: 0
                    })
                });
                arrId2.forEach(j => {
                    arrObj2.push({
                        id: j,
                        num: 0
                    })
                });
                data.forEach(k => {
                    arrObj.forEach(l => {
                        k.standardId === l.id ? l.num ++ : l.num;
                    })
                    arrObj2.forEach(l => {
                        k.subitemId === l.id ? l.num ++ : l.num;
                    })
                });
                data.forEach(m => {
                    arrObj.forEach((n,index) => {
                        if(m.standardId === n.id){
                            if(arrId.includes(m.standardId)){
                                m.mergeCol = n.num;
                                arrId.splice(arrId.indexOf(m.standardId),1);
                            }else{
                                m.mergeCol = 0;
                            }
                        }
                    });

                    arrObj2.forEach((n,index) => {
                        if(m.subitemId === n.id){
                            if(arrId2.includes(m.subitemId)){
                                m.mergeCol2 = n.num;
                                arrId2.splice(arrId2.indexOf(m.subitemId),1);
                            }else{
                                m.mergeCol2 = 0;
                            }
                        }
                    });

                })
            },
            handleSpan({ row, column, rowIndex, columnIndex }){
                if (columnIndex === 1 ) {
                    return {
                        rowspan: row.mergeCol === 0 ? 0:row.mergeCol,
                        colspan: row.mergeCol === 0 ? 0:1
                    };
                }
                if (columnIndex === 2 ) {
                    return {
                        rowspan: row.mergeCol2 === 0 ? 0:row.mergeCol2,
                        colspan: row.mergeCol2 === 0 ? 0:1
                    };
                }
            },
            formatDate(date, fmt) {
                if (/(y+)/.test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
                }
                let o = {
                    'M+': date.getMonth() + 1,
                    'd+': date.getDate(),
                    'h+': date.getHours(),
                    'm+': date.getMinutes(),
                    's+': date.getSeconds()
                };
                for (let k in o) {
                    if (new RegExp(`(${k})`).test(fmt)) {
                        let str = o[k] + '';
                        fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
                    }
                }
                return fmt;
            },
            padLeftZero(str) {
                return ('00' + str).substr(str.length);
            },
        }
    }
</script>

<style scoped>

</style>
